//
//  AlbumListTableViewController.swift
//  Media
//
//  Created by han on 2021/6/8.
//

import UIKit

class AlbumListTableViewController: UITableViewController {
    
    var dataSource = [AssetsGroup]()
    
    let assetsManger = AssetsManager.shared
    let thumbnailSize = CGSize(width: 64 * UIScreen.main.scale, height: 64 * UIScreen.main.scale)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        commonInit()
    }
    
    func commonInit() {
        DispatchQueue.global().async {
            self.dataSource = self.assetsManger.fetchAllAlbums(.all)
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    }
}

extension AlbumListTableViewController {
    override func numberOfSections(in tableView: UITableView) -> Int { 1 }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { self.dataSource.count }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: AlbumListCell.identifier, for: indexPath) as! AlbumListCell
        cell.titleLabel.text = dataSource[indexPath.row].name
        if let asset = dataSource[indexPath.row].firstObject {
            cell.representedAssetIdentifier = asset.localIdentifier
            assetsManger.cachingImageManager.requestImage(for: asset, targetSize: thumbnailSize, contentMode: .aspectFill, options: nil) { image, _ in
                if cell.representedAssetIdentifier == asset.localIdentifier {
                    cell.thumImageView.image = image
                }
            }
        }
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        switch indexPath.row {
        case 0:
           break
        
        default:
            break
        }
    }
}
